package com.yuyou.fn.timer.task;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.examples.Example;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import com.yuyou.fn.analyze.service.IDataStatisticsService;
import com.yuyou.fn.analyze.service.IIndexStatisticsService;
import com.yuyou.fn.analyze.vo.*;
import com.yuyou.fn.common.service.IEmailService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.Period;
import com.yuyou.fn.educational.service.IPeriodService;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.UserNotifyConfig;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IUserNotifyConfigService;
import com.yuyou.fn.platform.vo.NotifyConfigDetailVo;
import com.yuyou.fn.platform.vo.NotifyConfigVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/9.
 */
@JobHander(value = "DealUserEmailNotifyTask")
@Component
public class DealUserEmailNotifyTask extends IJobHandler {

    @Resource
    private IPeriodService periodService;

    @Resource
    private IUserNotifyConfigService userNotifyConfigService;

    @Resource
    private IIndexStatisticsService indexStatisticsService;

    @Resource
    private IDataStatisticsService dataStatisticsService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private IEmailService emailService;

    @Override
    public ReturnT<String> execute(String... params) throws Exception {
        List<UserNotifyConfig> userNotifyConfigList = userNotifyConfigService.findNotifyConfigByWay(0);
        List<AreaTeam> areaTeamList = areaTeamService.findAllAreaTeam();
        Map<Long, AreaTeam> areaTeamMap = BeanUtils.toMap(areaTeamList, "areaTeamId");
        Example<Period> example = Period.createExample();
        List<Period> periodList = periodService.findListByExample(example);
        Map<Long, Period> periodMap = BeanUtils.toMap(periodList, "periodId");
        if (Utils.checkListNotEmpty(userNotifyConfigList)) {
            for (UserNotifyConfig userNotifyConfig : userNotifyConfigList) {
                Long userId = userNotifyConfig.getUserId();
                try {

                /*[{type:"","conf":[{"areaTeamId":"","periodId":""}]}]*/
                    String notifyConfig = userNotifyConfig.getNotifyConfig();
                    StringBuffer content = new StringBuffer();
                    content.append("您好！以下是截止到昨天的基础业务数据，请查收：\n");
                    List<NotifyConfigVo> notifyConfigVoList = JSONObject.parseArray(notifyConfig, NotifyConfigVo.class);
                    for (NotifyConfigVo notifyConfigVo : notifyConfigVoList) {

                        List<NotifyConfigDetailVo> notifyConfigDetailVoList = notifyConfigVo.getConf();
                        Map<Long, List<NotifyConfigDetailVo>> areaTeamNotifyConfigDetailMap = BeanUtils.toGroup(notifyConfigDetailVoList, "areaTeamId");

                        if (notifyConfigVo.getType() == null) {
                            continue;
                        }
                        if (notifyConfigVo.getType() == 0) {/*预收*/
                            for (Map.Entry<Long, List<NotifyConfigDetailVo>> entry : areaTeamNotifyConfigDetailMap.entrySet()) {
                                Long areaTeamId = entry.getKey();
                                List<Long> busTeamIds = dataStatisticsService.findPermissionBusTeam(Arrays.asList(entry.getKey()), userId);
                                AreaTeam areaTeam = areaTeamMap.get(areaTeamId);
                                content.append(" \n\n" + (areaTeam == null ? "" : areaTeam.getName()));
                                List<NotifyConfigDetailVo> notifyConfigDetailVos = entry.getValue();
                                List<Long> periodIds = BeanUtils.toList(notifyConfigDetailVos, "periodId");
                                periodIds = Utils.removeDuplicate(periodIds);

                                for (Long periodId : periodIds) {
                                    BigDecimal advanceAmount = BigDecimal.ZERO;
                                    BigDecimal targetAmount = BigDecimal.ZERO;
                                    Period period = periodMap.get(periodId);
                                    for (Long busTeamId : busTeamIds) {
                                        BusTeamPeriodAdvanceVo busTeamPeriodAdvanceVo = indexStatisticsService.findBusTeamPeriodAdvance(areaTeamId, busTeamId, periodId, Utils.formatDate(new Date(), "yyyy-MM-dd"));
                                        if (busTeamPeriodAdvanceVo != null) {
                                            advanceAmount = advanceAmount.add(busTeamPeriodAdvanceVo.getAdvanceAmount());
                                            targetAmount = targetAmount.add(busTeamPeriodAdvanceVo.getTargetAmount());
                                        }
                                    }
                                 /*春季总预收453625.00元，预收进度：49%；暑假总预收3547365.00元，预收进度：57%；*/
                                    content.append(period == null ? "" : period.getPeriodName() + "总预收" + advanceAmount + "元,预收进度：" + Utils.getPercent(advanceAmount.toString(), targetAmount.toString(), 2) + ";");
                                }

                            }
                        } else if (notifyConfigVo.getType() == 1) {/*人数*/
                            for (Map.Entry<Long, List<NotifyConfigDetailVo>> entry : areaTeamNotifyConfigDetailMap.entrySet()) {
                                Long areaTeamId = entry.getKey();
                                List<Long> busTeamIds = dataStatisticsService.findPermissionBusTeam(Arrays.asList(entry.getKey()), userId);
                                AreaTeam areaTeam = areaTeamMap.get(areaTeamId);
                                content.append(" \n\n" + (areaTeam == null ? "" : areaTeam.getName()));
                                List<NotifyConfigDetailVo> notifyConfigDetailVos = entry.getValue();
                                List<Long> periodIds = BeanUtils.toList(notifyConfigDetailVos, "periodId");
                                periodIds = Utils.removeDuplicate(periodIds);

                                for (Long periodId : periodIds) {
                                    Integer studentRegNum = 0;
                                    Integer withStudentNum = 0;
                                    Period period = periodMap.get(periodId);
                                    for (Long busTeamId : busTeamIds) {
                                        BusTeamPeriodStudentNumVo busTeamPeriodStudentNumVo = indexStatisticsService.findBusTeamPeriodStudentNum(areaTeamId, busTeamId, periodId, Utils.formatDate(new Date(), "yyyy-MM-dd"));
                                        if (busTeamPeriodStudentNumVo != null) {
                                            studentRegNum = studentRegNum + busTeamPeriodStudentNumVo.getRegStudentNum();
                                            withStudentNum = withStudentNum + busTeamPeriodStudentNumVo.getWithStudentNum();
                                        }
                                    }
                               /* 春季报读人数 4344 ，同期人数 3736；*/
                                    content.append(period == null ? "" : period.getPeriodName() + "报读人数" + studentRegNum + "，同期人数" + withStudentNum + ";");
                                }
                            }
                        } else if (notifyConfigVo.getType() == 2) {
                            for (Map.Entry<Long, List<NotifyConfigDetailVo>> entry : areaTeamNotifyConfigDetailMap.entrySet()) {
                                Long areaTeamId = entry.getKey();
                                List<Long> busTeamIds = dataStatisticsService.findPermissionBusTeam(Arrays.asList(entry.getKey()), userId);
                                AreaTeam areaTeam = areaTeamMap.get(areaTeamId);
                                content.append(" \n\n" + (areaTeam == null ? "" : areaTeam.getName()));
                                List<NotifyConfigDetailVo> notifyConfigDetailVos = entry.getValue();
                                List<Long> periodIds = BeanUtils.toList(notifyConfigDetailVos, "periodId");
                                periodIds = Utils.removeDuplicate(periodIds);


                                for (Long periodId : periodIds) {
                                    Integer totalPersonNum = 0;
                                    Integer totalBranchNum = 0;
                                    Period period = periodMap.get(periodId);
                                    for (Long busTeamId : busTeamIds) {
                                        BusTeamPeriodBranchNumVo busTeamPeriodBranchNumVo = indexStatisticsService.findBusTeamPeriodBranchNum(areaTeamId, busTeamId, periodId, Utils.formatDate(new Date(), "yyyy-MM-dd"));
                                        if (busTeamPeriodBranchNumVo != null) {
                                            totalPersonNum = totalPersonNum + busTeamPeriodBranchNumVo.getTotalPersonNum();
                                            totalBranchNum = totalBranchNum + busTeamPeriodBranchNumVo.getTotalBranchNum();
                                        }
                                    }
                               /* 春季人均科数 2.03 ；*/
                                    Double AvgNum=0d;
                                    if (totalPersonNum!=0){
                                        AvgNum = (double) (totalBranchNum / (double) totalPersonNum);
                                    }
                                    content.append(period == null ? "" : period.getPeriodName() + "人均科数 " + new BigDecimal(AvgNum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + ";");
                                }
                            }
                        } else if (notifyConfigVo.getType() == 3) {
                            for (Map.Entry<Long, List<NotifyConfigDetailVo>> entry : areaTeamNotifyConfigDetailMap.entrySet()) {
                                Long areaTeamId = entry.getKey();
                                List<Long> busTeamIds = dataStatisticsService.findPermissionBusTeam(Arrays.asList(entry.getKey()), userId);
                                AreaTeam areaTeam = areaTeamMap.get(areaTeamId);
                                content.append(" \n\n" + (areaTeam == null ? "" : areaTeam.getName()));
                                List<NotifyConfigDetailVo> notifyConfigDetailVos = entry.getValue();
                                List<Long> periodIds = BeanUtils.toList(notifyConfigDetailVos, "periodId");
                                periodIds = Utils.removeDuplicate(periodIds);

                                for (Long periodId : periodIds) {
                                    Integer sequentialNum = 0;
                                    Integer stepNum = 0;
                                    Integer nowPeriodNum = 0;
                                    Period period = periodMap.get(periodId);
                                    for (Long busTeamId : busTeamIds) {
                                        BusTeamPeriodSeqStepNumVo busTeamPeriodSeqStepNumVo = indexStatisticsService.findBusTeamPeriodSeqStepNum(areaTeamId, busTeamId, periodId);
                                        if (busTeamPeriodSeqStepNumVo != null) {
                                            sequentialNum = sequentialNum + busTeamPeriodSeqStepNumVo.getSequentialNum();
                                            stepNum = stepNum + busTeamPeriodSeqStepNumVo.getStepNum();
                                            nowPeriodNum = nowPeriodNum + busTeamPeriodSeqStepNumVo.getNowPeriodNum();
                                        }
                                    }
                               /* 春季顺期续读科数 4344 ，顺期续读率 45%，跨期续读科数 7653，跨期续读率 42%；*/
                                    content.append(period == null ? "" : period.getPeriodName() + "顺期续读科数:" + sequentialNum + "，顺期续读率:" + Utils.getPercent(sequentialNum.toString(), nowPeriodNum.toString(), 2) +
                                            ",跨期续读科数:" + stepNum + ",跨期续读率:" + Utils.getPercent(stepNum.toString(), nowPeriodNum.toString(), 2)
                                            + ";");
                                }
                            }
                        } else if (notifyConfigVo.getType() == 4) {
                            for (Map.Entry<Long, List<NotifyConfigDetailVo>> entry : areaTeamNotifyConfigDetailMap.entrySet()) {
                                Long areaTeamId = entry.getKey();
                                List<Long> busTeamIds = dataStatisticsService.findPermissionBusTeam(Arrays.asList(entry.getKey()), userId);
                                AreaTeam areaTeam = areaTeamMap.get(areaTeamId);
                                content.append(" \n\n" + (areaTeam == null ? "" : areaTeam.getName()));
                                List<NotifyConfigDetailVo> notifyConfigDetailVos = entry.getValue();
                                List<Long> periodIds = BeanUtils.toList(notifyConfigDetailVos, "periodId");
                                periodIds = Utils.removeDuplicate(periodIds);

                                for (Long periodId : periodIds) {
                                    Integer busTeamQuota = 0;
                                    Integer busTeamEffectiveRegAmount = 0;
                                    Integer withBusTeamQuota = 0;
                                    Integer withBusTeamEffectiveRegAmount = 0;
                                    Period period = periodMap.get(periodId);
                                    for (Long busTeamId : busTeamIds) {
                                        BusTeamPeriodClassRegNumVo busTeamPeriodClassRegNumVo = dataStatisticsService.findBusTeamPeriodClassRegNumVo(areaTeamId, busTeamId, periodId);
                                        if (busTeamPeriodClassRegNumVo != null) {
                                            busTeamQuota = busTeamQuota + busTeamPeriodClassRegNumVo.getBusTeamQuota();
                                            busTeamEffectiveRegAmount = busTeamEffectiveRegAmount + busTeamPeriodClassRegNumVo.getBusTeamEffectiveRegAmount();
                                            withBusTeamQuota = withBusTeamQuota + busTeamPeriodClassRegNumVo.getWithBusTeamQuota();
                                            withBusTeamEffectiveRegAmount = withBusTeamEffectiveRegAmount + busTeamPeriodClassRegNumVo.getWithBusTeamEffectiveRegAmount();
                                        }
                                    }
                               /* 春季满班率 45%，同比（去年同期）35%。*/
                                    content.append(period == null ? "" : period.getPeriodName() + "满班率:" + Utils.getPercent(busTeamEffectiveRegAmount.toString(), busTeamQuota.toString(), 2) +
                                            ",同比（去年同期）" + Utils.getPercent(withBusTeamEffectiveRegAmount.toString(), withBusTeamQuota.toString(), 2)
                                            + ";");
                                }
                            }
                        }
                    }
                    emailService.sendEmail(userNotifyConfig.getWayData(), "业务数据订阅日报" + Utils.formatDate(new Date(), "yyyy-MM-dd"), content.toString(), null, null);

                } catch (Exception e) {
                    XxlJobLogger.log("userId:"+userId+"业务数据订阅日报"+  Utils.formatDate(new Date(), "yyyy-MM-dd")+"失败:"+e.getMessage());
                }
            }

        }

        return ReturnT.SUCCESS;
    }


}
